package com.creating.mict.action;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.creating.mict.domain.Office;
import com.creating.mict.domain.User;
import com.creating.mict.service.IOfficeService;
import com.creating.mict.service.IUserService;
import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class LoginAction extends ActionSupport {
	
	@Resource
	private IUserService userService;
	@Resource
	private IOfficeService officeService;
	
	@Override
	public String execute() throws Exception {
		try {
			User user = new User();
			user = userService.getUserByLoginName(loginName);
			if(user == null ||  !(user.getPassword().equals(password))) {
				return "error";
			}
			
			Office offi = officeService.getOfficeByCode(user.getFoffice());
			HttpServletRequest request = ServletActionContext.getRequest();
			request.getSession().setAttribute("loginName", user.getLoginName());
			request.getSession().setAttribute("fname", user.getFname());
			request.getSession().setAttribute("loginType", user.getFtype());
			request.getSession().setAttribute("loginOffice", user.getFoffice());
			if(offi != null) {
				request.getSession().setAttribute("officeName", offi.getFname());
			}
			
			//登录成功后，需要把该用户显示至在线用户
//			User users=userService.getUserByLoginName(loginName);
//			user.setUserFlag("1");			//0代表未登陆，1代表登陆
//			userService.updateUser(user);	//更新在线状态
			if(user.getFtype().equals("1")) { //服务端
				return "success";
			} else if(user.getFtype().equals("2")) {
				return "client";
			} else {
				return "common";
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "error";
	}
	
	/**
	 * 
	* @Title: loginOut 
	* @Description: 退出登录
	* @param @return 
	* @return String    返回类型 
	* @throws
	 */
	public String loginOut() {
		HttpServletRequest request = ServletActionContext.getRequest();
		request.getSession().setAttribute("loginName", null);
		request.getSession().setAttribute("loginType", null);
		return "loginout";
	}

	
	private String loginName;
	private String password;

	
	/**
	 * @return the loginName
	 */
	public String getLoginName() {
		return loginName;
	}

	/**
	 * @param loginName the loginName to set
	 */
	public void setLoginName(String loginName) {
		this.loginName = loginName;
	}
	
	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
}
